import type { QueryOptions } from '@dataui/crud/interfaces';
import { FindManyOptions, FindOptionsWhere } from 'typeorm';
import { FindManyOptionsReq } from '../find-options';
import { transWhere } from './trans-where';

export function transOrmFind(
  findOptions: FindManyOptionsReq,
  options: {
    query?: QueryOptions;
  } = {}
): FindManyOptions {
  let ormWhere: FindOptionsWhere<unknown>;
  if (findOptions.where) {
    ormWhere = {};
    transWhere(findOptions.where, ormWhere);
  }
  const res = { ...findOptions, where: ormWhere };
  const { query } = options;
  if (query) {
    if (findOptions.withDeleted && !query.softDelete) {
      delete findOptions.withDeleted;
    }
    if (findOptions.cache && query.cache === false) {
      delete findOptions.cache;
    }
    if (findOptions.relations) {
      if (!query.join) {
        delete findOptions.relations;
      } else {
        // [ ]
      }
    }
  }
  return res;
}
